<?php
namespace Admin\Controller;
use Think\Controller;
class WxconfigController extends BaseController {

    //入口方法
	public function entry(){
	   $retk=$this->token();
       define("TOKEN", $retk['wxc_value']);
       //如果token开启返回签名认证，否则作为自动回复处理
       if($retk['wxc_status']==1){
       	   $this->valid();
       }else{
       	   $this->responseMsg();
       }
	}

	public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }

    public function responseMsg()
    {
        //get post data, May be due to the different environments
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

        //extract post data
        if (!empty($postStr)){
                /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
                   the best way is to check the validity of xml by yourself */
                libxml_disable_entity_loader(true);
                $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                $fromUsername = $postObj->FromUserName;
                $toUsername = $postObj->ToUserName;
                $keyword = trim($postObj->Content);
                $time = time();
                //文本回复模板
                $textTpl = "<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <Content><![CDATA[%s]]></Content>
                            <FuncFlag>0</FuncFlag>
                            </xml>";
                //图文消息回复模板             
                $pic_text="<xml>
							<ToUserName><![CDATA[toUser]]></ToUserName>
							<FromUserName><![CDATA[fromUser]]></FromUserName>
							<CreateTime>12345678</CreateTime>
							<MsgType><![CDATA[news]]></MsgType>
							<ArticleCount>2</ArticleCount>
							<Articles>
							<item>
							<Title><![CDATA[title1]]></Title> 
							<Description><![CDATA[description1]]></Description>
							<PicUrl><![CDATA[picurl]]></PicUrl>
							<Url><![CDATA[url]]></Url>
							</item>
							<item>
							<Title><![CDATA[title]]></Title>
							<Description><![CDATA[description]]></Description>
							<PicUrl><![CDATA[picurl]]></PicUrl>
							<Url><![CDATA[url]]></Url>
							</item>
							</Articles>
							</xml> ";            
                if(!empty( $keyword ))
                {   
                	///////////////////
		            $type=$this->returntype();
		            if($type==0){
		            	//文本回复
		                $reword=$this->returntext($keyword);
		                $msgType = "text";
	                    $contentStr = "Welcome to wechat world!";
	                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
	                    echo $resultStr;
		            }
		            ///////////////////
                    
                }else{
                    echo "Input something...";
                }

        }else {
            echo "";

            exit;
        }
    }
        
    private function checkSignature()
    {
        // you must define TOKEN by yourself
        if (!defined("TOKEN")) {
            throw new Exception('TOKEN is not defined!');
        }
        
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
                
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }
    //取数据里的token值
    function token(){
    	$map=array('wxc_key'=>'token');
    	$field=array('wxc_value','wxc_status');
        $list=simList(M('Wxconfig'),$map,$field,'find');
        return $list;
    }

    function returntype(){
    	$map=array('wxc_key'=>'returnType');
        $list=M('Wxconfig')->where($map)->getfield('wxc_value');
        return $list;
    }
    //文本回复
    function returntext(){
    	$keyword=I('keyword','hello');
    	$map=mapStatus('wxc');
        $map['wxk_word']=array('LIKE','%'.$keyword.'%');
        $list=M('Wxkeywords')->where($map)->getfield('wxk_textreturn');
        return $list;
    }
}              